import React from 'react';
import { message, Button } from 'antd';
import { WeaDialog, WeaCheckbox, WeaLocaleProvider, WeaNewScroll, WeaTools } from 'ecCom';
import objectAssign from 'object-assign';
import { isContain } from '../../../pc4backstage/portal4engine/util/common';

const getLabel = WeaLocaleProvider.getLabel;
import './css/style.css';

class WeaExportElements extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hpid: 0,
            loginview: 0,
            expage: 0,
            exce: 0,
            exchart: 0,
            exoutdata: 0,
            curPreHpid: '',
            curAftHpid: '',
            preElements: [],
            aftElements: [],
            elements: [],
            preEChecks: {},
            aftEChecks: {},
            visible: props.visible || false,
            title: props.title || getLabel(391239, '门户页面元素导出'),
        };
        this.onSetEChecks = this.onSetEChecks.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.onLoad = this.onLoad.bind(this);
        this.onExportData = this.onExportData.bind(this);
        this.isContain = this.isContain.bind(this);
        this.onSetECheck = this.onSetECheck.bind(this);
        this.getElementItem = this.getElementItem.bind(this);
        this.initEChecks = this.initEChecks.bind(this);
    }

    initEChecks() {
        const { loginview, preEChecks, aftEChecks } = this.state;
        let obj = {};
        let eids = [];
        obj[this.state.hpid] = eids;
        if (loginview === '1') {
            this.state.preEChecks = objectAssign({}, preEChecks, obj);
        } else {
            this.state.aftEChecks = objectAssign({}, aftEChecks, obj);
        }
    }

    // 入口
    onLoad(hpid, isExPages, callback) {
        this.onSetCurrent(hpid, '', callback);
        this.setState({
            hpid,
            visible: true,
            expage: isExPages,
            preElements: [],
            aftElements: [],
            preEChecks: {},
            aftEChecks: {},
        });
        if (this.state.loginview === '1') {
            this.setState({
                curPreHpid: hpid,
            });
        } else {
            this.setState({
                curAftHpid: hpid,
            });
        }
        () => this.initEChecks();
    }

    isContain(arr, element) {
        if (!arr) return false;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] == element) {
                return true;
            }
        }
        return false;
    }


    // 获取元素数据
    onSetCurrent(id, value, callback) {
        const { loginview, expage, exce, exchart, exoutdata } = this.state;
        WeaTools.callApi('/api/portal/portalexport/elements', 'POST', {
            hpid: id,
            expage,
            exce,
            exchart,
            exoutdata,
        }).then((data) => {
            if (data.status == '2') {
                message.error(data.errormsg);
                return;
            }
            if (loginview === '1') {
                this.preElements = data;
            } else {
                this.aftElements = data;
            }
            this.setState({
                elements: this.loginview === '1' ? this.preElements : this.aftElements,
            });
            if (typeof callback === 'function') callback(value);
        });
    }

    onSetEChecks(value) {
        const { loginview, preEChecks, aftEChecks } = this.state;
        let obj = {};
        let eids = [];
        if (value === '1') {
            this.elements.map((item) => {
                eids.push(item.id);
            });
        }
        obj[this.state.hpid] = eids;

        if (loginview === '1') {
            this.state.preEChecks = objectAssign({}, preEChecks, obj);
        } else {
            this.state.aftEChecks = objectAssign({}, aftEChecks, obj);
        }
    }


    onSetECheck(id, value) {
        const { hpid, loginview, curPreHpid, curAftHpid } = this.state;
        let { preEChecks, aftEChecks } = this.state;
        if (value === '1') {
            let obj = {};
            let arr = (loginview === '1' ? preEChecks[curPreHpid] || [] : aftEChecks[curAftHpid] || []);
            if (!isContain(arr, id)) arr.push(id);
            obj[hpid] = arr;
            if (loginview === '1') {
                this.setState({
                    preEChecks: objectAssign({}, preEChecks, obj),
                });
            } else {
                this.setState({
                    aftEChecks: objectAssign({}, aftEChecks, obj),
                });
            }
        } else if (loginview === '1') {
                if (preEChecks[hpid]) {
                    preEChecks[hpid].remove(id);
                    this.setState({
                        preEChecks,
                    });
                }
            } else if (aftEChecks[hpid]) {
                    aftEChecks[hpid].remove(id);
                    this.setState({
                        aftEChecks,
                    });
                }
    }

    getElementItem(item) {
       // const {eChecks}=this.state;
        let obj = (this.state.loginview === '1' ? this.state.preEChecks[this.state.curPreHpid] || [] : this.state.aftEChecks[this.state.curAftHpid] || []);
        let isCheck = this.isContain(obj, item.id);
        return (<div className="portalexport-step2-element-item" title={item.name} onClick={() => this.onSetECheck(item.id, (isCheck ? '0' : '1'))}>
            <div className="portalexport-step2-element-item-check">
                <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@yovqnt`} value={isCheck} />
            </div>
            <div className="portalexport-step2-element-item-title">
                {item.name}
            </div>
        </div>);
    }


    render() {
        const { visible, title, elements } = this.state;
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@t8w7nb`}
              visible={visible}
              title={title}
              icon="icon-coms-portal"
              iconBgcolor="#1a57a0"
              style={{ width: 800, height: 510 }}
              hasScroll={true}
              buttons={this.getButtons()}
              onCancel={this.onCancel}
            >
                <div className="portalexport-elements">
                    <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@wy7gis`} scrollId="portalexportStep2Elements" height={510}>
                        <div className="portalexport-elements-content" >
                        {elements.length ? elements.map(item => this.getElementItem(item)) : <div className="portalexport-step2-elements-nodata">
                            {getLabel(130561, '没有可以选择的元素！')}
                        </div>}
                        </div>
                    </WeaNewScroll>
                </div>
            </WeaDialog>
        );
    }


    onCancel() {
        this.setState({ visible: false, selectedRowKeys: [] });
        tableStore.setSelectedRowKeys([]);
        tableStore.tableUpdate({ datas: [] });
    }

    onExportData() {
        this.loading = true;
        const { preEChecks, aftEChecks } = this.state;
        let preObj = {};
        for (let key in preEChecks) {
            preObj[key] = preEChecks[key].join(',');
        }
        let aftObj = {};
        for (let key in aftEChecks) {
            aftObj[key] = aftEChecks[key].join(',');
        }
        WeaTools.callApi('/api/portal/portalexport/exportdata', 'POST', {
            jsonStr: JSON.stringify({
                preIds: preObj,
                aftIds: aftObj,
            }),
        }).then((data) => {
            if (data.status == '2') {
                message.error(data.errormsg);
                return;
            }
            this.loading = false;
            this.step += 1;
            window.location.href = data.fileName;
            setTimeout(() => {
                this.setState({
                    visible: false,
                });
            }, 1000);
        });
    }

    getButtons() {
        let buttons = [];
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qyug8q`} type="primary" size="large" onClick={() => this.onExportData()}>{getLabel(17416, '导出')}</Button>);
        return buttons;
    }
}

export default WeaExportElements;
